package com.rent.house.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rent.common.exception.BusinessException;
import com.rent.common.service.StorageService;
import com.rent.house.dao.PicDao;
import com.rent.house.pojo.entity.Pic;
import com.rent.house.service.PicService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@RequiredArgsConstructor
public class PicServiceImpl implements PicService {

    private final StorageService storageService;
    private final PicDao picDao;

    @Override
    @Transactional
    public Pic uploadHousePic(MultipartFile file, Long houseId, Boolean isMain) {
        // 主图覆盖逻辑
        if (Boolean.TRUE.equals(isMain)) {
            picDao.resetMainPic(houseId);
            picDao.deleteMainPicFile(houseId); // 先删旧文件
        }

        String url;
        try {
            url = storageService.upload("house",file);
        } catch (IOException e) {
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }

        Pic pic = new Pic();
        pic.setHouseId(houseId);
        pic.setUrl(url);
        pic.setMain(isMain ? 1 : 0);
        pic.setSort(picDao.nextSort(houseId));
        picDao.insert(pic);
        return pic;
    }

    @Override
    public void deletePic(Long id) {
        Pic pic = picDao.selectById(id);
        if (pic == null) return;

        try {
            storageService.delete(pic.getUrl());
        } catch (IOException e) {
            throw new BusinessException("文件删除失败: " + e.getMessage());
        }

        picDao.deleteById(id);
    }
    @Override
    public void saveHousePics(Long houseId, List<String> picUrls) {
        if (picUrls != null && !picUrls.isEmpty()) {
            for (int i = 0; i < picUrls.size(); i++) {
                Pic pic = new Pic();
                pic.setHouseId(houseId);
                pic.setUrl(picUrls.get(i));
                pic.setSort(i);
                pic.setMain(i == 0 ? 1 : 0); // 第一张图片设为主图
                picDao.insert(pic);
            }
        }
    }

    @Override
    public Page<Pic> listPics(Page<Pic> page, QueryWrapper<Pic> queryWrapper) {
        IPage<Pic> result = picDao.selectPage(page, queryWrapper);
        return new Page<Pic>(result.getCurrent(), result.getSize(), result.getTotal())
                .setRecords(result.getRecords());
    }

    @Override
    public List<Pic> list(QueryWrapper<Pic> queryWrapper) {
        return picDao.selectList(queryWrapper);
    }

}
